const express = require('express');
const router = express.Router()
// Mock 用户数据
let users = [
    {
        id: '1',
        name: "REYUN",
        addr: "朝阳区"
    },
    {
        id: '2',
        name: "JD",
        addr: "大兴区"
    }
]
// 校验中间件
let validate = function (req, res, next) {
    try {
        let { id } = req.params
        if (!id) throw new Error('id不得为空')
        next()
    } catch (error) {
        res.send({ code: 400, message: error.message })
    }
}

// 日志记录
let morgan = function (req, res, next) {
    req.requestTime = Date.now()
    let { requestTime, baseUrl, user } = req
    console.log(requestTime, baseUrl, user);
    next()
}
router.use(morgan)

// 路由
router
    .get('/:id?', validate, function (req, res) {
        try {
            let { id } = req.params
            let user = users.find(user => user.id === id)
            if (!user) throw new Error('未查找到该用户')
            res.send({ code: 200, data: user })
        } catch (error) {
            res.send({ code: 400, message: error.message })
        }
    })
    .post('/', function (req, res) {
        try {
            let lastUser = users[users.length - 1]
            let { id = 0 } = lastUser
            id = `${id * 1 + 1}`
            let newUser = {
                id
            }
            Object.assign(newUser, req.body)
            users.push(newUser)
            res.send({ code: 200, data: newUser })
        } catch (error) {
            res.send({ code: 400, message: error.message })
        }
    })
    .put('/:id?', validate, function (req, res) {
        try {
            let { params: { id }, body } = req
            let user = users.find(user => user.id === id)
            if (!user) throw new Error('未查找到该用户')
            if (body.id) {
                delete body.id
            }
            Object.assign(user, body)
            res.send({ code: 200, data: user })
        } catch (error) {
            res.send({ code: 400, message: error.message })
        }
    })


module.exports = router
